package com.desksoft.action;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.desksoft.common.Constant;
import com.desksoft.common.DateUtil;
import com.desksoft.common.MD5;
import com.desksoft.common.UUIDGenerator;
import com.desksoft.entity.User;
import com.desksoft.service.UserService;

/**
 * 用户控制器
 * @author forever
 *
 */

@Controller
@RequestMapping(value="/page/user")
public class UserController extends BaseController {

	@Autowired
	private UserService userService;
	
	@RequestMapping(value="/initPage",method=RequestMethod.GET)
	public String initLoginRegisterPage(HttpServletRequest request){
		
		return "/page/register.jsp";
	}
	
	
	@RequestMapping(value="/register",method=RequestMethod.POST)
	@ResponseBody
	public Object registerUser(HttpServletRequest request,User u,String inputRegisterRandomKey){
		Object randKey = request.getSession().getAttribute("randKey");
		//验证码错误 
		if(!(randKey != null && randKey.toString().equals(inputRegisterRandomKey))){
			return this.failMessage();
		}
		try{
			u.setPassWord(new MD5().getMD5ofStr(u.getPassWord()));
			u.setUserId(UUIDGenerator.get()); 
			u.setGmtDate(DateUtil.getCurrentDate());
			userService.registerUser(u);
		}catch (Exception e) {
			e.printStackTrace();
			return this.failMessage();
		}
		return this.successMessage();
	}
	
	/**
	 * 登陆
	 * @param request
	 * @param u
	 * @param inputRegisterRandomKey
	 * @return
	 */
	@RequestMapping(value="/login",method=RequestMethod.POST)
	@ResponseBody
	public Object loginUser(HttpServletRequest request,User u,String inputLoginRandomKey){
		Object randKey = request.getSession().getAttribute("randKey");
		//验证码错误 
		if(!(randKey != null && randKey.toString().equals(inputLoginRandomKey))){
			return this.failMessage();
		}
		try{
			u.setPassWord(new MD5().getMD5ofStr(u.getPassWord()));
			User user =  userService.loginUser(u);
			request.getSession().setAttribute(Constant.SESSION_USER_PREFIX+user.getUserId(), user);
		}catch (Exception e) {
			e.printStackTrace();
			return this.failMessage();
		}
		return this.successMessage();
	}
	
	/**
	 * 登陆
	 * @param request
	 * @param u
	 * @param inputRegisterRandomKey
	 * @return
	 */
	@RequestMapping(value="/validation",method=RequestMethod.POST)
	@ResponseBody
	public Object validationResgisterInfo(HttpServletRequest request,User u){
		Integer count = userService.isExistUser(u);
		if(count != 0){
			return this.failMessage();
		}
		return this.successMessage() ;
	}
}
